package LeetCode.exercise;

public class LC6 {
    public static void main(String[] args) {
        String s = "PAYPALISHIRING";
        System.out.println(convert(s, 3));
    }
    public static String convert(String s, int numRows) {
        if(numRows == 1){
            return s;
        }
        StringBuilder sb = new StringBuilder();
        if(numRows == 2){
            for(int i = 0; i < s.length(); i += 2){
                sb.append(s.charAt(i));
            }
            for(int i = 1; i < s.length(); i += 2){
                sb.append(s.charAt(i));
            }
            return sb.toString();
        }
        int d = 2 * numRows - 2;
        for(int i = 0; i < s.length(); i += d){
            sb.append(s.charAt(i));
        }
        int left = 2 * (numRows-3) + 2;
        int right = d - left;
        for(int start = 1; left >= 2; start++){
            for(int i = start, count = 0; i < s.length();){
                sb.append(s.charAt(i));
                count++;
                if(count % 2 == 1){
                    i += left;
                } else {
                    i += right;
                }
            }
            left -= 2;
            right += 2;
        }
        for(int i = numRows-1; i < s.length(); i += d){
            sb.append(s.charAt(i));
        }
        return sb.toString();
    }
}
